package com.singlemusic.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

public class FileUtils {
	/**
	 * 保存文件
	 * @param inputStream 文件流
	 * @param path	保存路径
	 * @param fileName 文件名
	 */
	public static boolean saveFile(InputStream inputStream, String path, String fileName){
		FileOutputStream fos = null;
		
		try {
			
			File file = new File(path);
			if(!file.exists()){
				file.mkdirs();
			}
			
				fos=new FileOutputStream(new File(path+"/"+fileName));
				byte[] buffer = new byte[1024*1024];
				int len = 0;
			
				while((len = inputStream.read(buffer))!=-1){
	                fos.write(buffer, 0, len); 
	                
				}
				fos.flush();
				fos.close();
				return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 
	 * @param path 文件路径
	 * @return 文件流
	 */
	public static void loadFile(String path, HttpServletResponse response){
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Content-Type","audio/mp3");
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			byte[] buffer = new byte[1024];
			int len = 0;
			bis = new BufferedInputStream(new FileInputStream(path));
			os = response.getOutputStream();
			while((len=bis.read(buffer))!=-1){
				os.write(buffer, 0, len);
			}
			bis.close();
			os.flush();
			os.close();
			
		} catch (Exception e) {
			// TODO: handle exception
			//e.printStackTrace();
		}
	}
}
